package com.pay.ioopos.support.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * IP获取工具
 *
 * @author Moyq5
 * @since 2020/2/26 18:45
 */
public class IpUtil {

    public static String getIp(Context context) {

        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

        // 网络未连接
        if (info == null || !info.isConnected()) {
            return null;
        }

        if (info.getType() == ConnectivityManager.TYPE_MOBILE) {    // 当前使用2G/3G/4G网络
            Enumeration<NetworkInterface> niEnum;
            try {
                niEnum = NetworkInterface.getNetworkInterfaces();
            } catch (SocketException e) {
                return null;
            }
            NetworkInterface ni;
            Enumeration<InetAddress> iaEnum;
            InetAddress ia;
            while (niEnum.hasMoreElements()) {
                ni = niEnum.nextElement();
                iaEnum = ni.getInetAddresses();
                while (iaEnum.hasMoreElements()) {
                    ia = iaEnum.nextElement();
                    if (!ia.isLoopbackAddress() && ia instanceof Inet4Address) {
                        return ia.getHostAddress();
                    }
                }
            }
        } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {    // 当前使用无线网络
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());    // 得到IPV4地址
            return ipAddress;
        }
        return null;
    }

    /**
     * 将得到的int类型的IP转换为String类型
     */
    private static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }
}
